package com.soft.controller;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.soft.dto.CommentAddRequest;
import com.soft.dto.CommentResponse;
import com.soft.entity.Comment;
import com.soft.entity.User;
import com.soft.service.CommentService;
import com.soft.service.SensitiveWordService;
import com.soft.service.UserService;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 评论接口（/comment）：
 * - 支持多态关联（relatedType + relatedId），兼容旧的 worklogId
 * - 新增过滤敏感词，保留 originalContent
 * - 提供带回复树的查询接口
 */
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @Autowired
    private UserService userService;
    
    @Autowired
    private SensitiveWordService sensitiveWordService;

    /** 新增评论：支持 relatedType/relatedId 或兼容 worklogId；会进行敏感词过滤 */
    @PostMapping("/add")
    public boolean addComment(@RequestBody CommentAddRequest request) {
    Comment comment = new Comment();
        
    // STEP 1：解析关联信息
    // 支持新的字段格式（relatedId + relatedType）；兼容旧的 worklogId
        if (request.getRelatedId() != null && request.getRelatedType() != null) {
            comment.setRelatedType(request.getRelatedType());
            comment.setRelatedId(request.getRelatedId());
            comment.setCreatorId(request.getCreatorId() != null ? request.getCreatorId() : 1);
        } else {
            // 兼容旧的worklogId格式
            comment.setRelatedType("worklog");
            comment.setRelatedId(request.getWorklogId());
            comment.setCreatorId(1); // TODO: 从当前登录用户获取
        }
        
    // STEP 2：内容校验与敏感词过滤
        String originalContent = request.getContent();
        if (originalContent == null || originalContent.trim().isEmpty()) {
            return false;
        }
        
        // 保存原始内容
        comment.setOriginalContent(originalContent);
        
        try {
            String filteredContent = sensitiveWordService.filterSensitiveContent(originalContent);
            comment.setContent(filteredContent);
        } catch (Exception e) {
            // 如果敏感词服务出错，直接使用原内容
            System.err.println("敏感词过滤服务异常，使用原内容: " + e.getMessage());
            comment.setContent(originalContent);
        }
        comment.setCreateTime(LocalDateTime.now());
        
    // STEP 3：设置回复关系（可选）
        if (request.getReplyTo() != null) {
            comment.setReplyTo(request.getReplyTo());
        }
        
    // STEP 4：写入数据库
    return commentService.addComment(comment);
    }

    /** 删除评论：先校验存在性，再删除 */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<?> deleteComment(@PathVariable Integer id) {
        try {
            System.out.println("尝试删除评论ID: " + id);
            
            // STEP 1：存在性校验
            Comment existingComment = commentService.getCommentById(id);
            if (existingComment == null) {
                System.out.println("评论不存在: " + id);
                return ResponseEntity.badRequest().body("评论不存在");
            }
            
            System.out.println("找到评论: " + existingComment.getContent());
            
            // STEP 2：执行删除
            boolean result = commentService.deleteComment(id);
            System.out.println("删除结果: " + result);
            
            // STEP 3：返回结果
            if (result) {
                return ResponseEntity.ok(true);
            } else {
                return ResponseEntity.badRequest().body("删除失败");
            }
        } catch (Exception e) {
            // STEP 4：异常处理
            System.err.println("删除评论时发生异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body("删除评论时发生异常: " + e.getMessage());
        }
    }

    /** 更新评论内容（简单直改） */
    @PutMapping("/update")
    public boolean updateComment(@RequestBody Comment comment) {
        return commentService.updateComment(comment);
    }

    @GetMapping("/get/{id}")
    public Comment getComment(@PathVariable Integer id) {
        return commentService.getCommentById(id);
    }

    /** 按工作日志ID查询评论（旧接口，relatedType=worklog） */
    @GetMapping("/list/worklog/{worklogId}")
    public List<Comment> listCommentsByWorklog(@PathVariable Integer worklogId) {
        return commentService.listCommentsByWorklogId(worklogId);
    }

    // 新增：按日程ID查询（related_type = 'schedule'）供前端 /comment/list/schedule/{id} 使用
    /** 按日程ID查询评论（relatedType=schedule） */
    @GetMapping("/list/schedule/{scheduleId}")
    public List<Comment> listCommentsBySchedule(@PathVariable Integer scheduleId) {
        return commentService.listCommentsByScheduleId(scheduleId);
    }
    
    // 新增：返回包含回复关系的评论数据
    /** 返回包含回复关系的评论（工作日志） */
    @GetMapping("/worklog/{worklogId}/with-replies")
    public ResponseEntity<List<CommentResponse>> getCommentsWithRepliesByWorklogId(@PathVariable Integer worklogId) {
        List<CommentResponse> comments = commentService.listCommentsWithRepliesByWorklogId(worklogId);
        return ResponseEntity.ok(comments);
    }
    
    /** 返回包含回复关系的评论（日程） */
    @GetMapping("/schedule/{scheduleId}/with-replies")
    public ResponseEntity<List<CommentResponse>> getCommentsWithRepliesByScheduleId(@PathVariable Integer scheduleId) {
        List<CommentResponse> comments = commentService.listCommentsWithRepliesByScheduleId(scheduleId);
        return ResponseEntity.ok(comments);
    }

    /** 管理端：列出所有评论（需 X-User-Id 为 admin） */
    @GetMapping("/list/all")
    public Object listAll(HttpServletRequest req) {
        String h = req != null ? req.getHeader("X-User-Id") : null;
        try {
            Integer uid = h != null && !h.isEmpty() ? Integer.valueOf(h) : null;
            User u = uid != null ? userService.getById(uid) : null;
            if (u == null || u.getRole() == null || !"admin".equalsIgnoreCase(u.getRole())) {
                return org.springframework.http.ResponseEntity.status(403).body("forbidden");
            }
        } catch (NumberFormatException ex) {
            return org.springframework.http.ResponseEntity.status(403).body("forbidden");
        }
        return commentService.listAllForAdmin();
    }
}
